
package cc.bookcloud.tool.ocr.controller;


import com.alibaba.fastjson.JSON;
import cc.bookcloud.tool.ocr.common.JResult;
import cc.bookcloud.tool.ocr.common.upload.FileMeta;
import cc.bookcloud.tool.ocr.common.upload.UploadFileRequ;
import cc.bookcloud.tool.ocr.common.upload.UploadFileResp;
import cc.bookcloud.tool.ocr.common.upload.UserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@Api(tags = "一体化编译发版辅助小工具", value = "一体化编译发版辅助小工具")
@RequestMapping("/release")
public class FileOperateController {




    // 默认bucket
    private static final String _BUCKET_DEFAULT = "jzsoft";

    // 访问路径
    private static final String _ACCESS_PATH = "/oss/download?file=";

    /**
     * 文件上传
     *
     * @param upload
     * @return
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public JResult<List<UploadFileResp>> upload(UploadFileRequ upload) {
        log.info("[OSS文件上传] 请求参数==> 文件数量：" + upload.getFiles().size() + " ,目录（自定义）：" + upload.getModuleDir() + ",租户:" + upload.getTenantCode());
        String tenantCode = upload.getTenantCode();
        JResult<List<UploadFileResp>> result = JResult.build();
        List<UploadFileResp> files = new ArrayList<>();
        try {
            List<MultipartFile> fileList = upload.getFiles();
            for (MultipartFile file : fileList) {
                    String fileType = file.getContentType();

                    long fileSize = file.getSize();
                String originName = file.getOriginalFilename();

                //String filePath=_ACCESS_PATH + enAccessParam;
                UploadFileResp uploadFileResp = new UploadFileResp();
                uploadFileResp.setContentType(fileType);
                //uploadFileResp.setFilePath(filePath);
                uploadFileResp.setOriginName(originName);
                uploadFileResp.setFileSize(fileSize);
                // String enStr = URLEncoder.encode(accessParams, "UTF-8");
                log.info(" [OSS文件上传] 响应结果==>" + JSON.toJSONString(uploadFileResp));
                files.add(uploadFileResp);
                result.ok(files);
            }
        } catch (Exception e) {
            result.failed("上传文件失败:" + e.getMessage());
            log.error("*** [OSS文件上传] 上传文件发生了异常", e);
        }
        return result;
    }

    /**
     * 下载文件
     *
     * @param resp
     */
    @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public void download(HttpServletRequest request, HttpServletResponse resp) throws UnsupportedEncodingException {
        String requestParameter = request.getParameter("file");
        // String deStr = URLDecoder.decode(requestParameter, "UTF-8");
        FileMeta fileMeta = FileMeta.build().decrypt(requestParameter);
        log.info(" 下载文件参数：" + JSON.toJSONString(fileMeta));
        FastByteArrayOutputStream fbos = null;
        ServletOutputStream out = null;
        try {
            fbos = new FastByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int len;
           // GetObjectResponse readObject = minioClient.getObject(objectArgs);

//            while ((len = readObject.read(buf)) != -1) {
//                fbos.write(buf, 0, len);
//            }
            fbos.flush();
            byte[] bytes = fbos.toByteArray();
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("application/force-download");// 设置强制下载不打开
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileMeta.getOriginName(), "UTF-8"));
            out = resp.getOutputStream();
            out.write(bytes);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fbos != null) {
                fbos.close();
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    /**
     * 用户Demo演示
     *
     * @param resp
     */
    @ApiOperation(value = "用户Demo演示")
    @GetMapping("/demo/user")
    public JResult<UserEntity> userDemo(HttpServletRequest request, HttpServletResponse resp) {
        log.info("============= 收到 请求 ============");
        JResult<UserEntity> jResult = JResult.build();
        UserEntity userEntity = new UserEntity();
        userEntity.setId("9001");
        userEntity.setName("金政平台");
        userEntity.setQq("342535242");
        userEntity.setVxin("WX000990");
        jResult.ok(userEntity);
        return jResult;

    }



    /**
     * 文件上传
     *
     * @param files
     * @return
     */
    @ApiOperation(value = "文件上传")
    @PostMapping("/upload/files")
    public JResult<List<FileMeta>> uploadFiles(@RequestParam("files") MultipartFile[] files,HttpServletRequest request) throws IOException, ServletException {
        log.info("[OSS文件上传] 请求参数==> 文件数量：" +files.length);
        List<Part> list = (List<Part>) request.getParts();
        Object lst =  request.getParameter("files");
        //String files = request.getParameter("files");
        JResult<List<FileMeta>>  result = JResult.build();
        List<FileMeta> fmList  = new ArrayList<>();

        try {
            for (MultipartFile file : files) {
                FileMeta fm = new FileMeta();
                String fileType = file.getContentType();
                String name = file.getOriginalFilename();
                long  size = file.getSize();
                fm.setOriginName(name);
                fm.setContentType(fileType);
                fm.setFileSize(size);
                fmList.add(fm);
                log.info("-- 文件名称："+name+",大小："+size+",类型："+fileType);
            }
            result.ok(fmList);
        } catch (Exception e) {
            result.failed("上传文件失败:" + e.getMessage());
            log.error("*** [OSS文件上传] 上传文件发生了异常", e);
        }
        return result;
    }



}
